package com.example.snut_system.services.impl;


import com.example.snut_system.common.AppResult;
import com.example.snut_system.common.ResultCode;
import com.example.snut_system.dao.UserMapper;
import com.example.snut_system.exception.ApplicationException;
import com.example.snut_system.model.User;
import com.example.snut_system.services.IUserService;
import com.example.snut_system.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author ⽐特就业课
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        // 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //2.查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if (existsUser != null) {
            //打印日志
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //
// 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
// 性别赋默认值
            user.setGender((byte) 2);
        }
// 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if (row != 1) {
// 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " +
                    user.getUsername());
// 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
// 记录⽇志
        log.info("新增⽤⼾成功：username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        // 非空校验
        if (StringUtil.isEmpty(username)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }
}